#include "AddDialog.h"

AddDialog::AddDialog()
{
    layout_main = new QGridLayout;

    label_id = new QLabel();
    label_name = new QLabel();
    label_author = new QLabel();

    input_id = new QLineEdit();
    input_name = new QLineEdit();
    input_author = new QLineEdit();

    button_add = new QPushButton();
}

AddDialog::~AddDialog()
{
    delete button_add;

    delete input_author;
    delete input_name;
    delete input_id;

    delete label_author;
    delete label_name;
    delete label_id;

    delete layout_main;
}

void AddDialog::init_view_main()
{
    setWindowTitle("添加图书");
    setFixedSize(300, 160);

    layout_main->setSpacing(2);    //设置控件距离
    setLayout(layout_main);

    label_id->setStyleSheet("QLabel{font:12px;padding: 5px 15px 5px 15px;}");
    label_name->setStyleSheet("QLabel{font:12px;padding: 5px 15px 5px 15px;}");
    label_author->setStyleSheet("QLabel{font:12px;padding: 5px 15px 5px 15px;}");

    label_id->setText("编号：");
    label_name->setText("书名：");
    label_author->setText("作者：");

    input_id->setStyleSheet("QLabel{font:15px;padding: 0px 5px 0px 5px;}");
    input_name->setStyleSheet("QLabel{font:15px;padding: 0px 5px 0px 5px;}");
    input_author->setStyleSheet("QLabel{font:15px;padding: 0px 5px 0px 5px;}");

    input_id->setClearButtonEnabled(true);
    input_name->setClearButtonEnabled(true);
    input_author->setClearButtonEnabled(true);

    layout_main->addWidget(label_id, 0, 0, 1, 1);
    layout_main->addWidget(input_id, 0, 1, 1, 2);
    layout_main->addWidget(label_name, 1, 0, 1, 1);
    layout_main->addWidget(input_name, 1, 1, 1, 2);
    layout_main->addWidget(label_author, 2, 0, 1, 1);
    layout_main->addWidget(input_author, 2, 1, 1, 2);

    button_add->setText("添加");
    button_add->setToolTip("添加图书");
    QObject::connect(button_add,&QPushButton::clicked,button_add,[&](){
        QString id = input_id->text().isEmpty() ? NULL: input_id->text();
        QString name = input_name->text().isEmpty() ? NULL: input_name->text();
        QString author = input_author->text().isEmpty() ? NULL: input_author->text();

        if(add_book(id, name, author))
        {
            setWindowTitle("添加成功");
            delete this;
        }
        else
        {
            setWindowTitle("添加失败");
        }
    }); //设置监听
    layout_main->addWidget(button_add, 3, 1, 1, 1);
}

int AddDialog::add_book(QString id, QString name, QString author)
{
    if(id.isNull() || name.isNull()  || author.isNull() )
    {
        return 0;
    }

    SQLHelper sql_helper;
    sql_helper.connect();

    QVector<QString> v_book;

    v_book.push_back(id);   // id
    v_book.push_back(name);    // name
    v_book.push_back(author);    // author

    return sql_helper.insert_table("books", &v_book);
}
